/**
 * This file is part of ossecdb-extjs.
 *
 * Copyright (C) 2011 Brendan Johnston
 *
 * Contact: brendan@johnston.net.au
 *
 * Project: http://code.google.com/p/ossecdb-extjs/
 *
 * License: http://www.gnu.org/licenses/gpl-3.0.html
 */

Ext.define('OssecWeb.view.alert.Panel', {
	extend: 'Ext.panel.Panel',
	alias: 'widget.alertpanel',
	initComponent: function () {
		
		var alertGrid = Ext.create('OssecWeb.view.alert.Grid', {
			stateId: 'sAlerts',
			stateful: true,
			title: 'Alerts',
			region: 'center',
			listeners: {
				statesave: function (stateful, state, options) {
					delete state.sort;
					delete state.filters;
				}
			}
		});
	
		var dataPanel = Ext.create('Ext.panel.Panel', {
			region: 'south',
			html: [
				'<span class="msg">',
					'Select rows to view log data ...',
				'</span>'
			].join(''),
			split: true,
			height: 100,
			autoScroll: true,
			collapsed: true,
			collapsible: true,
			animCollapse: true,
			collapseMode: 'mini',
			hideCollapseTool: true,
			bodyCls: 'logpanel'
		});

		var alertToolbar = Ext.create('Ext.toolbar.Paging', {
			store: 'Alerts',
			cls: 'alertpagingtoolbar',
			prependButtons: true,
			items: ['Page size', {
				stateId: 'sPageSize',
				stateful: true,
				stateEvents: ['change'],
				xtype: 'numberfield',
				width: 47,
				step: 10,
				value: 30, 
				minValue: 10,
				maxValue: 100,
				allowBlank: false,
				allowDecimals: false,
				listeners: {
					change: function (field, newValue, oldValue, options) {
						var store = alertGrid.getStore();
						store.pageSize = newValue;
						store.loadPage(1);
					},
					staterestore: function (stateful, state, options) {
						if (state.value) {
							stateful.setValue(state.value);
						}
					}
				},
				getState: function () {
					return {
						value: this.getValue()
					};
				}
			}, '-']
		});

		Ext.apply(this, {
			border: false,
			layout: 'border',
			items: [
				alertGrid, 
				dataPanel
			],
			bbar: alertToolbar
		});

		var model = alertGrid.getSelectionModel();
		model.setSelectionMode('MULTI');
		model.addListener('selectionchange', function(model, selected) {
			if (selected.length) {
				var html = [];
				for (var i = 0; i < selected.length; i++) {
					html.push(
						'<span class="id">(' + selected[i].data.alert_id + ')</span> ' + addLinks(selected[i].data.full_log)
					);
				}
				html = html.join('<br>');
				dataPanel.update(html);
				dataPanel.expand();
			}
			// Source: http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
			function addLinks (text) {
				var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
				return text.replace(exp, '<a href="$1" target="_blank">$1</a>'); 
			}
		});

		this.callParent(arguments);
	}
});